<?php

/**
 * ArticleModel.php 注释
 * 
 * @package 
 * @subpackage 
 * @author rendong01 rendong237@126.com
 * 
 * : tool.php 8 2011-11-16 11:23:09Z rendong237@gmail.com $
 */
class ArticleModel{
	/**
	 * 数据库对象
	 *
	 * @var Mysql
	 */
	private $db;
	
	/**
	 * 构造方法
	 *
	 * @param Mysql $db
	 */
	public function __construct($db)
	{
		$this->db = $db;
	}
	
	/**
	 * 添加
	 */
	public function add( array $value )
	{
		$v = array();
//		$v["aid"] = (int)$value["aid"];
		$v["title"] = $value["title"];
		$v["content"] = $value["content"];
		$v["pubtime"] = $value["pubtime"];
		$v["seq"] = (int)$value["seq"];
		$v["adminid"] = (int)$value["adminid"];
		
		$this->db->insert("article", $v);
		$this->updateCache();
	}
	
	/**
	 * 修改
	 */
	public function change($aid, array $value)
	{
		$v = array();
		isset($value["title"]) && $v["title"] = $value["title"];
		isset($value["content"]) && $v["content"] = $value["content"];
		isset($value["pubtime"]) && $v["pubtime"] = $value["pubtime"];
		isset($value["seq"]) && $v["seq"] = (int)$value["seq"];
		isset($value["adminid"]) && $v["adminid"] = (int)$value["adminid"];

		$this->db->update("article", $v, 'aid=' . (int)$aid);
		$this->updateCache();
	}
	
	/**
	 * 删除
	 */
	public function del($aid)
	{
		$this->db->delete("article", 'aid=' .  (int)$aid);
		$this->updateCache();
	}
	
	/**
	 * 读取列表
	 *
	 * @param Integer $nowp
	 * @param Integer $per_page
	 */
	public function fetchAll($nowp, $per_page)
	{
		$where = '';		
		$totalNum = $this->db->fetchOne ('select count(*) from article ' . $where);
        
        require_once APP . '/application/models/Util.php';
        
        $pageInfo = Util::page ($totalNum, $per_page, $nowp);
        $start    = $pageInfo ['start'];
        $list     = $this->db->fetchAll ('select t1.*,t2.username from article t1 left join admin t2 on t2.id=t1.adminid' . $where .' order by seq desc, aid desc limit ' . $start . ',' . $per_page);
        
        return Array ('page' => $pageInfo['page'], 'list' => $list);
	}
	
	/**
	 * 显示
	 */
	public function show($aid)
	{
		return $this->db->fetchRow("select * from `article` where aid=\"?\"", array($aid));
	}
	
	
	/**
	 * 读取前10篇文章
	 *
	 * @return unknown
	 */
	public function fetchTop10()
	{
		$result = FileCache::getInstance()->get("article_top10");
		if ($result == null){
			$result = $this->db->fetchAll("select aid,title,pubtime from article order by seq desc,aid desc limit 10");
			
			FileCache::getInstance()->set("article_top10", $result);
		}
		
		return $result;
	}
	
	private function updateCache()
	{
		FileCache::getInstance()->delete("article_top10");
	}
}